<%@ page contentType="application/json;charset=UTF-8" language="java" %><%--
--%><%@ page import="java.util.List" %><%--
--%><%@ page import="com.google.appengine.api.datastore.Key" %><%--
--%><%@ page import="spacecrack.Game" %><%--
--%><%@ page import="spacecrack.GameManager" %><%--
--%><%@ page import="spacecrack.NameRandomizer" %><%--
--%><%@ page import="spacecrack.Player" %><%--
--%><%@ page import="spacecrack.PlayerManager" %><%--
--%><%@ page import="o.json.JSONFactory" %><%--
--%><%@ page import="o.json.JSONWriter" %><%--
--%><%--@ include file="games.json" --%><%--
--%><%

	final GameManager gm = new GameManager();
	final PlayerManager pm = new PlayerManager();

	String action = request.getParameter("action");
	if (action == null) {
		System.out.println("Load");
	}
	if (action != null && action.equalsIgnoreCase("clear")) {
		System.out.println("Clear");
		gm.clearGames();
	}
	if (action != null && action.equalsIgnoreCase("create")) {
		System.out.println("Create");
		final List<Player> players = pm.loadPlayers();
		if (!players.isEmpty()) {
			String id      = NameRandomizer.get(5);
			Player owner   = players.get((int)(Math.random()*players.size()));
			String name    = owner.getName() + "'s Game";
			String status  = "Active";

			final Game game = new Game(id, name, owner.getKey(), status);
			for (int i = 0; i < 3; ++i) {
				Player player  = players.get((int)(Math.random()*players.size()));
				game.addPlayerKey(player.getKey());
			}
			if (!gm.gameExists(id)) {
				gm.storeGame(game);
			}
		}
	}

	final List<Game> games = gm.loadGamesWithPlayers();

	final JSONWriter writer = new JSONWriter();
	final JSONFactory f = new JSONFactory();
	writer.write(f.create(games));

%><%= writer.toString() %>
